package com.chao.socket.tcp.b;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClient {

    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        ByteArrayOutputStream baos = null;
        InputStream is = null;
        try {
            // 服务端的ip和端口
            InetAddress address = InetAddress.getByName("localhost");
            socket = new Socket(address, 8090);
            // 获取输入流，写出要发送的数据
            os = socket.getOutputStream();
            os.write("客户端请求连接".getBytes());
            // 通知服务器，输出完毕
            socket.shutdownOutput();

            is = socket.getInputStream();
            baos = new ByteArrayOutputStream();
            int length = 0;
            byte[] buffer = new byte[1024];
            while ((length = is.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
            System.out.println("接收到服务端的消息：" + baos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                assert is != null;
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
